package com.qf.air.service.impl;

import com.qf.air.service.EchcatsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author songfei
 * @Date 2021/11/5 21:25
 * @Version 1.0
 */
@Service
public class EchcatsServiceImpl implements EchcatsService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public List<Map> airTopFive() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("air");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.terms("airtopfive").field("districtName").size(5));
        sourceBuilder.size(0);
        request.source(sourceBuilder);

        SearchResponse resp = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        Terms terms = resp.getAggregations().get("airtopfive");

        List<Map> result = new ArrayList<>();

        for (Terms.Bucket bucket : terms.getBuckets()) {
            Map map = new HashMap();
            map.put("name",bucket.getKey());
            map.put("value",bucket.getDocCount());
            result.add(map);
        }
        return result;

    }
}
